package com.sntk.organauthomanager.infrastructure.convert;

import com.sntk.organauthomanager.domain.model.UserResource;
import com.sntk.organauthomanager.domain.model.UserResourceIdentify;
import com.sntk.organauthomanager.infrastructure.db.entity.UserResourceEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: UserResourceConvert
 * @author: wgchao
 * @createTime: 2020/9/16 9:51 AM
 * @Description: TODO
 */
@Component
public class UserResourceConvert {
    public List<UserResourceEntity> convert(UserResource userResource){
        if(userResource.getResources()!=null && !userResource.getResources().isEmpty()){
            List<UserResourceEntity> userResourceEntities = new ArrayList<>();
            for(String resource : userResource.getResources()){
                UserResourceEntity userResourceEntity = new UserResourceEntity();
                userResourceEntity.setUname(userResource.getIdentify().getUname());
                userResourceEntity.setInstitutionNumber(userResource.getIdentify().getInstitutionNumber());
                userResourceEntity.setResourceMark(resource);
                userResourceEntities.add(userResourceEntity);
            }
            return userResourceEntities;
        }
        return null;
    }

    public UserResource convert(List<UserResourceEntity> userResourceEntities){
        if(userResourceEntities==null || userResourceEntities.isEmpty()){
            return null;
        }
        Set<String> resources = new HashSet<>();
        for(UserResourceEntity userResourceEntity : userResourceEntities){
            resources.add(userResourceEntity.getResourceMark());
        }
        return new UserResource(new UserResourceIdentify(userResourceEntities.get(0).getUname(),
                userResourceEntities.get(0).getInstitutionNumber()), resources);
    }
}
